# -*- coding: utf-8 -*-

############################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#############################################################################

"""
Decorator function for identity authentication
"""

from asyncio.proactor_events import constants
from dataclasses import dataclass
from distutils.log import error
from email import header
import functools
from datetime import date

from flask import request, current_app
from flask_caching import Cache
import redis
# from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# from itsdangerous import TimedSerializer as Serializer
from authlib.jose import jwt,JoseError
import utils.message.response as response
from utils.wraps.urlcost import cost_count_wraps

# _allToken = dict()



cache = redis.Redis(host='10.206.0.115', port=6379, db=10, password='SKadmin123_456')

def create_token(user_id, operator_id, case_id, role, play=""):
    """
    create token
    :param api_user:user id
    :return: token
    """
   
    
    # s = Serializer(current_app.config["SECRET_KEY"], expires_in=2592000)
   
    # token = s.dumps({"adminId": user_id, "operatorId": operator_id,
    #                  "caseId": case_id, "role": role}).decode("ascii")
    # _allToken[str(user_id)] = token
    
    header ={'alg':'HS256'}
    key= current_app.config["SECRET_KEY"]
    data ={"adminId": user_id, "operatorId": operator_id,
                      "caseId": case_id, "role": role,"playground_limit":play}
    # data.update(data)
    # print(data)
    token = jwt.encode(header=header,payload=data,key=key).decode("ascii")
    # _allToken[str(user_id)] = token
    cache.set(token, str(user_id), ex=3*24*60*60) # 3天
    # print(token)
    return token


def delete_token(token):
    """
        check token
        :param token:
        :return: bool
    """
     
    # _allToken[str(userId)] = ""
    cache.set(token,"",ex=3*60) #3分钟
    return True


def getUserInfoFromAuth(token) -> dict:
    """
    check token
    :param token:
    :return: user info dict
    """
     
    # s = Serializer(current_app.config["SECRET_KEY"])
    # try:
    #     
    #     data = s.loads(token)
    # except Exception:
    #     return {}
    # 


    key = current_app.config["SECRET_KEY"]
    #
    # data = jwt.decode(token, key)
    # return data
    try:
        data = jwt.decode(token,key)
        return data
    except:
        return {}



def login_required(view_func):
    @functools.wraps(view_func)
    def wraper(*args, **kwargs):
        try:
          
            token = request.headers["Authorization"]
        except Exception:
         
            return response.make_response_1507()

        key = current_app.config["SECRET_KEY"]
        try:
            # if _allToken[str(data["adminId"])] == "":
            if not cache.get(token):
                return response.make_response_1506()
        except:
            # cache.set(str(data["adminId"]),"",ex=3*60)
            return response.make_response_15068()
        
        # s = Serializer(current_app.config["SECRET_KEY"])
        # try:
        #     data = s.loads(token)
        #     if _allToken[str(data["adminId"])] == "":
        #         return response.make_response_1506()
        # except:
        #     return response.make_response_1506()
        
        return view_func(*args, **kwargs)

    return wraper
